<template>
  <div class="app-container transfer-search">
    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <div class="search-header">
        <h3>
          <i class="el-icon-guide"></i>
          公交换乘查询
        </h3>
        <p>选择起始和目标站点，系统将为您推荐最优的换乘方案</p>
      </div>

      <el-form :model="searchForm" ref="searchForm" :inline="true" label-width="80px" class="search-form">
        <el-form-item label="起始站点" prop="fromStationId" required>
          <el-select
            v-model="searchForm.fromStationId"
            placeholder="请选择起始站点（可搜索）"
            filterable
            remote
            :remote-method="searchStations"
            :loading="stationLoading"
            style="width: 220px;"
            @change="onFromStationChange">
            <el-option
              v-for="station in stationOptions"
              :key="station.id"
              :label="station.stationName"
              :value="station.id">
              <span style="float: left">{{ station.stationName }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px">{{ station.stationCode }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="exchange-btn">
          <el-button
            type="text"
            icon="el-icon-refresh"
            @click="exchangeStations"
            title="交换起点和终点"
            class="exchange-button">
          </el-button>
        </el-form-item>

        <el-form-item label="目标站点" prop="toStationId" required>
          <el-select
            v-model="searchForm.toStationId"
            placeholder="请选择目标站点（可搜索）"
            filterable
            remote
            :remote-method="searchStations"
            :loading="stationLoading"
            style="width: 220px;"
            @change="onToStationChange">
            <el-option
              v-for="station in stationOptions"
              :key="station.id"
              :label="station.stationName"
              :value="station.id">
              <span style="float: left">{{ station.stationName }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px">{{ station.stationCode }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="换乘偏好">
          <el-radio-group v-model="searchForm.mode">
            <el-radio label="default">综合优化</el-radio>
            <el-radio label="fast">最短时间</el-radio>
            <el-radio label="comfort">舒适出行</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="handleSearch"
            :loading="searching"
            :disabled="!canSearch">
            {{ searching ? '查询中...' : '查询换乘' }}
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 搜索结果 -->
    <div class="search-results" v-if="searchResults">
      <el-card shadow="never">
        <div class="result-header">
          <h4>
            <span class="station-name">{{ searchResults.fromStationName }}</span>
            <i class="el-icon-right"></i>
            <span class="station-name">{{ searchResults.toStationName }}</span>
          </h4>
          <div class="result-meta">
            <span>查询耗时: {{ searchResults.queryTime }}ms</span>
            <span>找到 {{ searchResults.transferPlans ? searchResults.transferPlans.length : 0 }} 个方案</span>
          </div>
        </div>

        <!-- 换乘方案列表 -->
        <div class="transfer-plans" v-if="searchResults.transferPlans && searchResults.transferPlans.length > 0">
          <div
            v-for="(plan, index) in searchResults.transferPlans"
            :key="plan.planId"
            class="transfer-plan"
            :class="{ 'recommended': index === 0 }">

            <!-- 方案头部 -->
            <div class="plan-header">
              <div class="plan-badge">
                <span class="plan-id">方案{{ plan.planId }}</span>
                <span class="plan-type" :class="getPlanTypeClass(plan.planType)">
                  {{ getPlanTypeName(plan.planType) }}
                </span>
                <el-rate
                  v-if="index === 0"
                  :value="5"
                  :max="5"
                  disabled
                  show-score
                  score-template="推荐"
                  class="recommend-rate">
                </el-rate>
              </div>

              <div class="plan-summary">
                <div class="summary-item">
                  <i class="el-icon-time"></i>
                  <span>{{ plan.totalTime }}分钟</span>
                </div>
                <div class="summary-item">
                  <i class="el-icon-connection"></i>
                  <span>{{ plan.transferCount }}次换乘</span>
                </div>
                <div class="summary-item">
                  <i class="el-icon-location"></i>
                  <span>{{ plan.totalDistance }}公里</span>
                </div>
                <div class="summary-item" v-if="plan.walkingTime > 0">
                  <i class="el-icon-walking"></i>
                  <span>步行{{ plan.walkingTime }}分钟</span>
                </div>
              </div>
            </div>

            <!-- 线路详情 -->
            <div class="route-details">
              <div class="route-timeline">
                <div
                  v-for="(segment, segIndex) in plan.routeSegments"
                  :key="segIndex"
                  class="timeline-item">

                  <!-- 起始站点（只在第一个段显示） -->
                  <div v-if="segIndex === 0" class="station-point start-station">
                    <div class="station-dot start-dot"></div>
                    <div class="station-info">
                      <div class="station-name">{{ segment.boardStationName }}</div>
                      <div class="station-action">上车</div>
                    </div>
                  </div>

                  <!-- 线路段 -->
                  <div class="route-segment">
                    <div class="route-line"></div>
                    <div class="route-info">
                      <div class="route-name">{{ segment.routeName }}</div>
                      <div class="route-details-text">
                        经过{{ segment.stationCount || 1 }}站 · {{ segment.segmentTime }}分钟
                      </div>
                    </div>
                  </div>

                  <!-- 换乘点（不是最后一个段时显示） -->
                  <div v-if="segIndex < plan.routeSegments.length - 1" class="station-point transfer-station">
                    <div class="station-dot transfer-dot"></div>
                    <div class="station-info">
                      <div class="station-name">{{ segment.alightStationName }}</div>
                      <div class="station-action">
                        {{ getTransferText(segment.transferType) }}
                        <span v-if="segment.transferWalkTime > 0" class="walk-time">
                          (步行{{ segment.transferWalkTime }}分钟)
                        </span>
                      </div>
                    </div>
                  </div>

                  <!-- 终点站（最后一个段） -->
                  <div v-if="segIndex === plan.routeSegments.length - 1" class="station-point end-station">
                    <div class="station-dot end-dot"></div>
                    <div class="station-info">
                      <div class="station-name">{{ segment.alightStationName }}</div>
                      <div class="station-action">下车</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 方案操作 -->
            <div class="plan-actions">
              <el-button size="small" type="text" @click="showPlanDetail(plan)">
                <i class="el-icon-view"></i> 查看详情
              </el-button>
              <el-button size="small" type="text" @click="showOnMap(plan)">
                <i class="el-icon-map-location"></i> 地图显示
              </el-button>
            </div>
          </div>
        </div>

        <!-- 无结果提示 -->
        <div v-else class="no-results">
          <el-empty
            description="未找到合适的换乘方案"
            :image-size="80">
            <el-button type="primary" @click="resetSearch">重新搜索</el-button>
          </el-empty>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <div v-if="!searchResults && !searching" class="empty-state">
      <el-empty
        description="请选择起始和目标站点开始查询"
        :image-size="120">
      </el-empty>
    </div>
  </div>
</template>

<script>
import { searchTransfer } from '@/api/bus/transfer'
import { listStations } from '@/api/bus/stations'

export default {
  name: 'TransferSearch',
  data() {
    return {
      // 搜索表单
      searchForm: {
        fromStationId: null,
        toStationId: null,
        mode: 'default'
      },
      // 站点选项
      stationOptions: [],
      allStations: [], // 存储所有站点数据，用于搜索筛选
      stationLoading: false,
      // 搜索状态
      searching: false,
      searchResults: null,
      // 选中的站点信息
      selectedFromStation: null,
      selectedToStation: null
    }
  },
  computed: {
    canSearch() {
      return this.searchForm.fromStationId && this.searchForm.toStationId &&
        this.searchForm.fromStationId !== this.searchForm.toStationId
    }
  },
  created() {
    this.loadStations()
  },
  methods: {
    /** 加载站点列表 */
    async loadStations() {
      try {
        // 加载所有站点，不分页
        const response = await listStations({
          pageNum: 1,
          pageSize: 10000 // 设置足够大的页面大小，获取所有站点
        })
        const stations = response.rows || []
        this.allStations = stations
        // 初始显示前100个站点，避免下拉框过长
        this.stationOptions = stations.slice(0, 100)
        console.log('加载站点数量:', this.allStations.length, '初始显示:', this.stationOptions.length)
      } catch (error) {
        console.error('加载站点列表失败', error)
        this.$message.error('加载站点列表失败')
      }
    },

    /** 搜索站点 */
    searchStations(query) {
      if (query) {
        this.stationLoading = true
        // 从所有站点中筛选匹配的站点
        setTimeout(() => {
          const filtered = this.allStations.filter(station =>
            station.stationName.toLowerCase().includes(query.toLowerCase()) ||
            (station.stationCode && station.stationCode.toLowerCase().includes(query.toLowerCase()))
          )
          this.stationOptions = filtered
          this.stationLoading = false
        }, 200) // 添加轻微延迟，提供更好的用户体验
      } else {
        // 重置为所有站点
        this.stationOptions = [...this.allStations]
      }
    },

    /** 起始站点变化 */
    onFromStationChange(stationId) {
      this.selectedFromStation = this.stationOptions.find(s => s.id === stationId)
    },

    /** 目标站点变化 */
    onToStationChange(stationId) {
      this.selectedToStation = this.stationOptions.find(s => s.id === stationId)
    },

    /** 交换起点和终点 */
    exchangeStations() {
      const temp = this.searchForm.fromStationId
      this.searchForm.fromStationId = this.searchForm.toStationId
      this.searchForm.toStationId = temp

      const tempStation = this.selectedFromStation
      this.selectedFromStation = this.selectedToStation
      this.selectedToStation = tempStation
    },

    /** 执行搜索 */
    async handleSearch() {
      if (!this.canSearch) {
        this.$message.warning('请选择不同的起始和目标站点')
        return
      }

      this.searching = true
      try {
        const response = await searchTransfer(this.searchForm)
        this.searchResults = response.data

        if (!this.searchResults.transferPlans || this.searchResults.transferPlans.length === 0) {
          this.$message.warning('未找到合适的换乘方案，请尝试其他站点')
        } else {
          this.$message.success(`找到 ${this.searchResults.transferPlans.length} 个换乘方案`)
        }
      } catch (error) {
        console.error('换乘查询失败', error)
        this.$message.error('换乘查询失败，请稍后重试')
        this.searchResults = null
      } finally {
        this.searching = false
      }
    },

    /** 重置搜索 */
    resetSearch() {
      this.searchForm = {
        fromStationId: null,
        toStationId: null,
        mode: 'default'
      }
      this.searchResults = null
      this.selectedFromStation = null
      this.selectedToStation = null
      // 恢复初始站点选项（前100个）
      this.stationOptions = this.allStations.slice(0, 100)
    },

    /** 获取方案类型名称 */
    getPlanTypeName(planType) {
      const typeMap = {
        1: '最少换乘',
        2: '最短时间',
        3: '最短距离'
      }
      return typeMap[planType] || '综合方案'
    },

    /** 获取方案类型样式 */
    getPlanTypeClass(planType) {
      const classMap = {
        1: 'type-transfer',
        2: 'type-time',
        3: 'type-distance'
      }
      return classMap[planType] || 'type-default'
    },

    /** 获取换乘文本 */
    getTransferText(transferType) {
      const textMap = {
        0: '同站换乘',
        1: '站内换乘',
        2: '步行换乘'
      }
      return textMap[transferType] || '换乘'
    },

    /** 显示方案详情 */
    showPlanDetail(plan) {
      // TODO: 实现详情弹窗
      this.$message.info('详情功能开发中')
    },

    /** 在地图上显示 */
    showOnMap(plan) {
      // TODO: 实现地图显示
      this.$message.info('地图显示功能开发中')
    }
  }
}
</script>

<style scoped>
.transfer-search {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  margin-bottom: 20px;
  text-align: center;
}

.search-header h3 {
  color: #303133;
  margin: 0 0 8px 0;
  font-size: 24px;
}

.search-header p {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.search-form {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 20px;
}

.exchange-btn {
  margin: 0 10px;
}

.exchange-button {
  font-size: 18px;
  color: #409eff;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s;
}

.exchange-button:hover {
  background-color: #ecf5ff;
  transform: rotate(180deg);
}

.result-header {
  margin-bottom: 20px;
  text-align: center;
}

.result-header h4 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #303133;
}

.station-name {
  font-weight: bold;
  color: #409eff;
}

.result-meta {
  color: #909399;
  font-size: 12px;
}

.result-meta span {
  margin: 0 10px;
}

.transfer-plans {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.transfer-plan {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s;
}

.transfer-plan:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.transfer-plan.recommended {
  border-color: #409eff;
  background: linear-gradient(to right, #ecf5ff, #ffffff);
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f2f5;
}

.plan-badge {
  display: flex;
  align-items: center;
  gap: 10px;
}

.plan-id {
  background: #409eff;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.plan-type {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

.plan-type.type-transfer { background: #67c23a; }
.plan-type.type-time { background: #e6a23c; }
.plan-type.type-distance { background: #f56c6c; }
.plan-type.type-default { background: #909399; }

.recommend-rate {
  font-size: 12px;
}

.plan-summary {
  display: flex;
  gap: 20px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.summary-item i {
  color: #409eff;
}

.route-timeline {
  display: flex;
  flex-direction: column;
}

.timeline-item {
  display: flex;
  flex-direction: column;
}

.station-point {
  display: flex;
  align-items: center;
  margin: 10px 0;
}

.station-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 15px;
  flex-shrink: 0;
}

.start-dot { background: #67c23a; }
.transfer-dot { background: #e6a23c; }
.end-dot { background: #f56c6c; }

.station-info {
  display: flex;
  flex-direction: column;
}

.station-name {
  font-weight: bold;
  color: #303133;
  font-size: 14px;
}

.station-action {
  color: #909399;
  font-size: 12px;
}

.walk-time {
  color: #e6a23c;
}

.route-segment {
  display: flex;
  align-items: center;
  margin: 5px 0;
  padding-left: 6px;
}

.route-line {
  width: 2px;
  height: 30px;
  background: #409eff;
  margin-right: 13px;
}

.route-info {
  display: flex;
  flex-direction: column;
}

.route-name {
  font-weight: bold;
  color: #409eff;
  font-size: 14px;
}

.route-details-text {
  color: #909399;
  font-size: 12px;
}

.plan-actions {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f2f5;
  text-align: right;
}

.no-results {
  text-align: center;
  padding: 40px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .plan-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .plan-summary {
    flex-wrap: wrap;
    gap: 10px;
  }
}
</style>